package com.dick.base.aop;

import com.dick.base.service.OperateLogService;
import com.dick.base.util.SpelUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Aspect
@Order(1000)
@Component
public class OperateLogAspect {

    private static final Logger log = LoggerFactory.getLogger(OperateLogAspect.class);

    @Autowired
    private OperateLogService operateLogService;

    @Pointcut("@annotation(OperateLog)")
    public void operateLogPointcut() {

    }

    @Around(value = "operateLogPointcut() && @annotation(operateLog)", argNames = "jointPoint,operateLog")
    public Object aroundOperate(ProceedingJoinPoint joinPoint, OperateLog operateLog) throws Throwable{
        Object result = joinPoint.proceed(joinPoint.getArgs());
        try {
            String detail = operateLog.detail();
            if (!StringUtils.isEmpty(detail)) {
                detail = SpelUtil.generateKeyBySpel(detail, joinPoint);
            }
            operateLogService.addLog(operateLog.operate(), detail);
        } catch (Throwable t) {
            log.error("Add operate log failed!", t);
        }
        return result;
    }
}
